import logging


from django.db import DatabaseError
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler

from mars.utils.exceptions.enums import StatusCodeEnum
from mars.utils.exceptions.exceptions import APIException, BusinessException
from mars.utils.exceptions.result import R

# 获取在配置文件中定义的logger，用来记录日志
logger = logging.getLogger("django")


def exception_handler(exc, context):
    """
    自定义异常处理
    :param exc: 异常实例对象
    :param context: 抛出异常的上下文(包含request和view对象)
    :return: Response响应对象
    """
    # 调用drf框架原生的异常处理方法
    response = drf_exception_handler(exc, context)
    if response is None:
        view = context["view"]

        if isinstance(exc, BusinessException):
            # 业务异常处理
            r = R.set_result(exc.enum_cls)
            response = Response(r.error(exc.err_detail))

        elif isinstance(exc, APIException):
            # 业务异常处理
            r = R.set_result(exc.enum_cls)
            response = Response(r.error(exc.detail))
        elif isinstance(exc, DatabaseError):
            # 数据库异常
            r = R.set_result(StatusCodeEnum.DB_ERR)
            logger.error(r.error(), exc_info=True)
            # response = Response(
            #     StatusCodeEnum.SERVER_ERR.errmsg,
            #     status=status.HTTP_507_INSUFFICIENT_STORAGE,
            # )
            response = Response(
                r.error(StatusCodeEnum.SERVER_ERR.errmsg),
                status=status.HTTP_507_INSUFFICIENT_STORAGE,
            )


        elif isinstance(exc, Exception):
            # 服务器异常处理
            r = R.server_error()
            logger.error(r.error(), exc_info=True)
            response = Response(r.error(), r.code)
    else:
        # 同意处理返回格式，DRF框架已处理的异常
        r = R.server_error()
        logger.error(r.data(), exc_info=True)
        response = Response(r.error(exc.detail), response.status_code)

    return response
